<template>
  <div class="formwork--wrap">
    <div class="formwork--title">
      <div class="formwork--title--l">
        <div
          :class="['formwork--btn', { active: type == 'public' }]"
          @click="choseType('public')"
        >
          公共模板
        </div>
        <div
          :class="['formwork--btn', { active: type == 'personal' }]"
          @click="choseType('personal')"
        >
          个人模板
        </div>
        <div
          :class="['formwork--btn', { active: type == 'words' }]"
          @click="choseType('words')"
        >
          词库模板
        </div>
      </div>
      <div class="formwork--title--r" v-show="type == 'public' && canUploadAndDown">
        <a-space size="large">
          <ExUpload
            @getResult="getUploadData"
            :status="isImport"
            @changeStatus="changeStatus"
          />
          <!-- <download-excel
            class="download-excel"
            :fields="json_fields"
            worksheet="智能检测报告模板"
            name="智能检测报告模板"
            :fetch="getExcelData"
            :before-finish="downExcelFinish"
          >
            <span class="formwork--title--word">下载模板</span>
          </download-excel> -->
          <span class="formwork--title--word" v-preventReClick @click="exportPubReportTem">下载模板</span>
        </a-space>
      </div>
      <div class="formwork--title--r" v-show="type == 'personal'">
        <a-space size="large">
          <ExUpload
            @getResult="getUserUploadData"
            :status="isImport"
            @changeStatus="changeStatus"
          />
          <!-- <download-excel
            class="download-excel"
            :fields="json_fields"
            worksheet="个人智能检测报告模板"
            name="个人智能检测报告模板"
            :fetch="getUserExcelData"
            :before-finish="downExcelFinish"
          >
            <span class="formwork--title--word">下载模板</span>
          </download-excel> -->
          <span class="formwork--title--word" v-preventReClick @click="exportPerReportTem">下载模板</span>
        </a-space>
      </div>
      <div class="formwork--title--r" v-show="type == 'words' && canUploadAndDown">
        <a-space size="large">
          <SearchUpload
            @getResult="getSearchUploadData"
            :status="isSearchImport"
            @changeStatus="changeSearchStatus"
          />
          <!-- <download-excel
            class="download-excel"
            :fields="word_fields"
            worksheet="词库模板"
            name="词库模板"
            :fetch="getWordsData"
            :before-finish="downExcelFinish"
          >
            <span class="formwork--title--word">下载模板</span>
          </download-excel> -->
          <span class="formwork--title--word" v-preventReClick @click="exportWordsTem">下载模板</span>
        </a-space>
      </div>
    </div>
    <div class="formwork--con" v-show="type == 'public'">
      <div class="formwork--tree">
        <div class="symptom--tree--wrap2">
          <a-tree
            :tree-data="symptomData"
            @select="onSelect"
            class="symptom--tree"
            :replace-fields="{
              children: 'Symptoms',
            }"
          >
          </a-tree>
        </div>
      </div>
      <div class="formwork--tips--sub">超声影像所见:</div>
      <a-textarea
        placeholder="请输入"
        :rows="15"
        :value="seen"
        class="formwork--tips--inp"
      />
      <div class="formwork--tips--sub">超声影像诊断提示:</div>
      <a-textarea
        placeholder="请输入"
        :rows="15"
        :value="tips"
        class="formwork--tips--inp"
      />
    </div>
    <div class="formwork--con" v-show="type == 'personal'">
      <div class="formwork--tree">
        <div class="symptom--tree--wrap2">
          <a-tree
            :tree-data="usersymptomData"
            @select="onUserSelect"
            class="symptom--tree"
            :replace-fields="{
              children: 'usersymptoms',
            }"
          >
          </a-tree>
        </div>
      </div>
      <div class="formwork--tips--sub">超声影像所见:</div>
      <a-textarea
        placeholder="请输入"
        :rows="15"
        :value="personal_seen"
        class="formwork--tips--inp"
      />
      <div class="formwork--tips--sub">超声影像诊断提示:</div>
      <a-textarea
        placeholder="请输入"
        :rows="15"
        :value="personal_tips"
        class="formwork--tips--inp"
      />
    </div>
    <div class="formwork--con" v-show="type == 'words'">
      <a-select
        label-in-value
        :show-search="true"
        v-model="searchValue"
        :placeholder="placeholder2"
        class="select--search2"
        :filter-option="false"
        :not-found-content="null"
        @search="fetchSearch"
        @change="handleSearchChange"
        @focus="placeholder2 = ''"
        @blur="placeholder2 = '检索词条'"
      >
        <a-select-option
          v-for="d in searchResult"
          :key="d.value"
          :title="d.text"
        >
          {{ d.text }}
        </a-select-option>
      </a-select>
      <div class="keyboard--group2">
        <div
          v-for="item in keyboardListData"
          :key="item.key"
          class="keyboard--item"
        >
          {{ item.label }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ExUpload from "@/components/ExUpload";
import SearchUpload from "@/components/SearchUpload";
import { getAllSymptomSub, bulkCreateSymptomSubAndSym } from "@/api/SymptomSub";
import { getAllSymptom, getSymptom } from "@/api/symptom";
import { json_fields, word_fields } from "@/utils";
import { v4 as uuidv4 } from "uuid";
import {
  getAllSearch,
  getAllSearchSymbol,
  getSearchByCode,
} from "@/api/searchInfo";
import { bulkCreateSearch } from "@/api/searchInfo";
import dellSymptopmJson from "@/utils/dellSymptomJson";
import {
  getAllUserSymptomSub,
  bulkCreateUserSymptomSubAndSym,
} from "@/api/usersymptomSub";
import { getAllUserSymptom } from "@/api/userSymptom";
import { mapState } from "vuex";
import { exportXlsxFile } from "@/utils/exportFile";
export default {
  name: "FormWork",
  props: ["status", "who"],
  data() {
    return {
      type: "public", //public公共  personal个人 words词库
      json_fields: json_fields,
      word_fields: word_fields,
      symptomData: [],
      seen: "",
      tips: "",
      isImport: false, //导入公共模板状态
      isDownJson: false, //下载公共模板状态
      personal_seen: "",
      personal_tips: "",
      searchValue: "",
      placeholder2: "检索词条",
      keyboardListData: [], //常用词库
      searchResult: [],
      isSearchImport: false, //导入词库状态
      usersymptomData: [],
    };
  },
  computed: {
    ...mapState(["userInfo", "patUserInfo","SERVERBASE_URL"]),
    userid() {
      return this.$store.state.userInfo.id
    },
    //是否可以导入模板和下载模板
    canUploadAndDown() {
      if (
        this.userInfo.level == 1 ||
        this.userInfo.level == 2 ||
        this.userInfo.level == 5 
      ) {
        return true;
      } else {
        return false;
      }
    },
  },
  watch: {
    type(val) {
      if (val == "words") {
        this.initSymbol();
      } else if (val == "public") {
        this.initSym();
      } else if (val == "personal") {
        this.initUserSym();
      }
    },
    status: {
      immediate: true,
      handler(val) {
        if (val) {
          this.initSym();
        } else {
          this.type = "public";
          this.resetData();
        }
      },
    },
  },
  components: {
    ExUpload,
    SearchUpload,
  },
  methods: {
    choseType(type) {
      if (!type) {
        return;
      }
      this.type = type;
    },
    async initSym() {
      const allSym = await getAllSymptomSub(this.SERVERBASE_URL);
      const vm = this;
      if (allSym.data && allSym.data.length == 0) {
        const res = await getSymptom(this.SERVERBASE_URL);
        const { SymSubs, SymS } = dellSymptopmJson(res.data);
        const result = await bulkCreateSymptomSubAndSym(this.SERVERBASE_URL,{ SymSubs, SymS });
        console.log("初始化模板", result);
      } else {
        allSym.data.forEach(item=>{
          if(item.Symptoms.length > 0){
            item.Symptoms = item.Symptoms.sort((obj1, obj2) => obj1.snumber - obj2.snumber);
          }
        })
        allSym.data.sort((obj1, obj2) => obj1.snumber - obj2.snumber);
        console.log("所有的模板", allSym.data);
        vm.symptomData = allSym.data;
      }
    },
    //导入公共模版-获取导入数据
    async getUploadData(data) {
      console.log("导入数据", data);
      if (!data || data.length == 0) {
        this.$message.warning("数据为空！请填写数据！");
        return;
      }
      let key = false;
      let errInfo;
      data.forEach((item) => {
        if (!item["模板分类"] && !item["症状"] && !item["超声影像所见"]) {
          errInfo = `存在空的模板分类！空的症状！空的超声影像所见！`;
          key = true;
        } else if (
          !item["模板分类"] &&
          !item["症状"] &&
          !item["超声影像诊断提示"]
        ) {
          errInfo = `存在空的模板分类！空的症状！空的超声影像诊断提示！`;
          key = true;
        } else if (!item["模板分类"] && !item["症状"]) {
          errInfo = "存在空的模板分类！与空的症状！";
          key = true;
        } else if (!item["超声影像所见"] || !item["超声影像诊断提示"]) {
          errInfo = `${item["模板分类"]}某个值为空！`;
          key = true;
        } else if (!item["症状"]) {
          errInfo = `${item["模板分类"]}的症状值为空！`;
          key = true;
        } else if (!item["模板分类"]) {
          errInfo = "存在空的模板分类！";
          key = true;
        }
      });
      if (key) {
        this.$message.warning(`${errInfo}`);
        return;
      }

      const SymSubs = [];
      const SymS = [];
      const hadSymSu = {};
      data.forEach((item,index) => {
        if (!hadSymSu[item["模板分类"]]) {
          let symptomsubId = uuidv4();
          let symSubItem = {
            id: symptomsubId,
            title: item["模板分类"],
            snumber:index
          };
          let symItem = {
            id: uuidv4(),
            title: item["症状"],
            seen: item["超声影像所见"],
            tips: item["超声影像诊断提示"],
            symptomsubId,
            snumber:index
          };
          hadSymSu[item["模板分类"]] = symptomsubId;
          SymS.push(symItem);
          SymSubs.push(symSubItem);
        } else {
          let symItem = {
            id: uuidv4(),
            title: item["症状"],
            seen: item["超声影像所见"],
            tips: item["超声影像诊断提示"],
            symptomsubId: hadSymSu[item["模板分类"]],
            snumber:index
          };
          SymS.push(symItem);
        }
      });
      const res = await bulkCreateSymptomSubAndSym(this.SERVERBASE_URL, { SymSubs, SymS });
      if (res.code === 200) {
        console.log("导入数据", res.data);
        this.$message.success(`导入成功!`);
        this.initSym();
      } else {
        this.$message.error(`导入失败!`);
      }
    },
    //下载公共模版-获取数据库已有的模板
    async getExcelData() {
      const res = await getAllSymptom(this.SERVERBASE_URL);
      if (res.code == 200) {
        return res.data;
      } else {
        return [
          {
            subject: "腹部",
            symptom: "胆结石",
            seen: "胆囊@切面形态大小正常;形态饱满，切面大小约×mm@，@壁薄、光滑，;壁厚约mm，稍毛糙，@其腔内可见@一个强回声团;几个强回声团;多个强回声团;一不规则强回声区@，@大小约×mm;较大的约×mm;范围约×mm@，@改变体位可移动;改变体位无明显移动;形态可随体位改变@，后方伴声影。胆总管、肝内外胆管未见明显扩张。",
            tips: "@胆囊结石;胆囊多发性结石;胆囊泥沙样结石",
          },
        ];
      }
    },
    //下载公共报告模板
    async exportPubReportTem() {
      try {
        const report_data = await this.getExcelData(this.SERVERBASE_URL);
        if (report_data.length > 0) {
          const headerMapping = {
            subject: "模板分类",
            symptom: "症状",
            seen: "超声影像所见",
            tips: "超声影像诊断提示",
          };
          exportXlsxFile(report_data, headerMapping, "检测报告模板","report");
        } else {
          this.$message.error("暂无数据");
        }
      } catch (error) {
        console.log("exportReportTem :", error);
      }
    },
    async initUserSym() {
      try {
        const allSym = await getAllUserSymptomSub(this.SERVERBASE_URL, this.userid);
        if (allSym.data && allSym.data.length == 0) {
          this.$message.warning("请导入个人模板");
        }
        allSym.data.forEach(item=>{
          if(item.usersymptoms.length > 0){
            item.usersymptoms = item.usersymptoms.sort((obj1, obj2) => obj1.snumber - obj2.snumber);
          }
        })
        allSym.data.sort((obj1, obj2) => obj1.snumber - obj2.snumber);
        this.usersymptomData = allSym.data;
      } catch (error) {
        console.log("initUserSym", error);
      }
    },
    //导入个人模版-获取导入数据
    async getUserUploadData(data) {
      try {
        console.log("导入数据", data);
        if (!data || data.length == 0) {
          this.$message.warning("数据为空！请填写数据！");
          return;
        }
        let key = false;
        let errInfo;
        data.forEach((item) => {
          if (!item["模板分类"] && !item["症状"] && !item["超声影像所见"]) {
            errInfo = `存在空的模板分类！空的症状！空的超声影像所见！`;
            key = true;
          } else if (
            !item["模板分类"] &&
            !item["症状"] &&
            !item["超声影像诊断提示"]
          ) {
            errInfo = `存在空的模板分类！空的症状！空的超声影像诊断提示！`;
            key = true;
          } else if (!item["模板分类"] && !item["症状"]) {
            errInfo = "存在空的模板分类！与空的症状！";
            key = true;
          } else if (!item["超声影像所见"] || !item["超声影像诊断提示"]) {
            errInfo = `${item["模板分类"]}某个值为空！`;
            key = true;
          } else if (!item["症状"]) {
            errInfo = `${item["模板分类"]}的症状值为空！`;
            key = true;
          } else if (!item["模板分类"]) {
            errInfo = "存在空的模板分类！";
            key = true;
          }
        });
        if (key) {
          this.$message.warning(`${errInfo}`);
          return;
        }

        const SymSubs = [];
        const SymS = [];
        const hadSymSu = {};
        data.forEach((item,index) => {
          if (!hadSymSu[item["模板分类"]]) {
            let usersymptomsubId = uuidv4();
            let symSubItem = {
              id: usersymptomsubId,
              title: item["模板分类"],
              userid: this.userid,
              snumber:index
            };
            let symItem = {
              id: uuidv4(),
              title: item["症状"],
              seen: item["超声影像所见"],
              tips: item["超声影像诊断提示"],
              usersymptomsubId,
              userid: this.userid,
              snumber:index
            };
            hadSymSu[item["模板分类"]] = usersymptomsubId;
            SymS.push(symItem);
            SymSubs.push(symSubItem);
          } else {
            let symItem = {
              id: uuidv4(),
              title: item["症状"],
              seen: item["超声影像所见"],
              tips: item["超声影像诊断提示"],
              usersymptomsubId: hadSymSu[item["模板分类"]],
              userid: this.userid,
              snumber:index
            };
            SymS.push(symItem);
          }
        });
        const res = await bulkCreateUserSymptomSubAndSym(this.SERVERBASE_URL, { SymSubs, SymS,userid:this.userid });
        if (res.code === 200) {
          console.log("导入数据", res.data);
          this.$message.success(`导入成功!`);
          this.initUserSym();
        } else {
          this.$message.error(`导入失败!`);
        }
      } catch (error) {
        console.log("getUserUploadData", error);
      }
    },
    //下载个人模版-获取数据库已有的模板
    async getUserExcelData() {
      const res = await getAllUserSymptom(this.SERVERBASE_URL, this.userid);
      if (res.code == 200) {
        return res.data;
      } else {
        return [
          {
            subject: "腹部",
            symptom: "胆结石",
            seen: "胆囊@切面形态大小正常;形态饱满，切面大小约×mm@，@壁薄、光滑，;壁厚约mm，稍毛糙，@其腔内可见@一个强回声团;几个强回声团;多个强回声团;一不规则强回声区@，@大小约×mm;较大的约×mm;范围约×mm@，@改变体位可移动;改变体位无明显移动;形态可随体位改变@，后方伴声影。胆总管、肝内外胆管未见明显扩张。",
            tips: "@胆囊结石;胆囊多发性结石;胆囊泥沙样结石",
          },
        ];
      }
    },
    //下载个人报告模板
    async exportPerReportTem() {
      try {
        const report_data = await this.getUserExcelData(this.SERVERBASE_URL);
        if (report_data.length > 0) {
          const headerMapping = {
            subject: "模板分类",
            symptom: "症状",
            seen: "超声影像所见",
            tips: "超声影像诊断提示",
          };
          exportXlsxFile(report_data, headerMapping, "个人检测报告模板","report");
        } else {
          this.$message.error("暂无数据");
        }
      } catch (error) {
        console.log("exportReportTem :", error);
      }
    },
    //下载词库-获取数据库已有的模板
    async getWordsData() {
      const res = await getAllSearch(this.SERVERBASE_URL);
      if (res.data.length > 0) {
        return res.data.map((item) => {
          return {
            type: item.type,
            pinyin: item.pinyin,
            detail: item.detail,
          };
        });
      } else {
        return [];
      }
    },
    async exportWordsTem() {
      try {
        const words_data = await this.getWordsData(this.SERVERBASE_URL);
        if (words_data.length > 0) {
          const headerMapping = {
            type: "数据类型",
            pinyin: "拼音码",
            detail: "详细内容",
          };
          exportXlsxFile(words_data, headerMapping, "词库模板","words");
        } else {
          this.$message.error("暂无数据");
        }
      } catch (error) {
        console.log("exportWordsTem :", error);
      }
    },
    //下载完成回调
    downExcelFinish() {
      this.isDownJson = true;
      window.setTimeout(() => {
        this.isDownJson = false;
        this.$message.success("下载成功!");
      }, 10000);
    },
    //导入模板状态改变
    changeStatus() {
      this.isImport = true;
    },
    //选择公共模板
    onSelect(data, info) {
      const con = info.node._props.dataRef;
      if (con.seen) {
        this.seen = con.seen.replace(/(\n|\r|\r\n|↵)/g, "<br/>");
        this.tips = con.tips.replace(/(\n|\r|\r\n|↵)/g, "<br/>");
      }
      console.log(data);
      info.node.onExpand();
    },
    //
    onUserSelect(data, info) {
      const con = info.node._props.dataRef;
      if (con.seen) {
        this.personal_seen = con.seen.replace(/(\n|\r|\r\n|↵)/g, "<br/>");
        this.personal_tips = con.tips.replace(/(\n|\r|\r\n|↵)/g, "<br/>");
      }
      console.log(data);
      info.node.onExpand();
    },
    //初始化常用符号
    async initSymbol() {
      const res = await getAllSearchSymbol(this.SERVERBASE_URL);
      if (res.code === 200) {
        if (res.data && res.data.length !== 0) {
          this.keyboardListData = [];
          res.data.forEach((item) => {
            this.keyboardListData.push({
              key: item.detail,
              label: item.detail,
            });
          });
        } else {
          //   this.$message.error(`请导入常用词库!`);
          console.log("请导入常用词库!");
          this.keyboardListData = [];
        }
      }
    },
    async fetchSearch(value) {
      if (value) {
        const res = await getSearchByCode(this.SERVERBASE_URL, value);
        console.log("------常用符号---", res);
        if (res.code === 200) {
          if (res.data && res.data.length !== 0) {
            this.searchResult = [];
            res.data.forEach((item) => {
              this.searchResult.push({
                value: item.detail,
                text: item.detail,
              });
            });
          } else {
            this.searchResult = [];
          }
        }
      } else {
        this.searchResult = [];
      }
    },
    handleSearchChange(value) {
      console.log(value);
      this.searchResult = [];
      this.searchValue = "";
    },
    //获取导入常用词库数据
    async getSearchUploadData(data) {
      console.log("导入数据", data);
      if (!data || data.length == 0) {
        this.$message.warning("数据为空！请填写数据！");
        this.isSearchImport = false;
        return;
      }
      let searchArr = [];
      data.forEach((item) => {
        if (item["数据类型"] == "词库" && !item["拼音码"]) {
          this.$message.warning(`存在空的搜索词库拼音码！`);
          this.isSearchImport = false;
          return;
        }
        let searchItem = {
          id: uuidv4(),
          type: item["数据类型"] == "符号" ? "symbol" : item["数据类型"] == 'symbol' ? 'symbol' :"word",
          pinyin: item["拼音码"] ? item["拼音码"] : "",
          detail: item["详细内容"],
        };
        searchArr.push(searchItem);
      });
      const res = await bulkCreateSearch(this.SERVERBASE_URL, searchArr);
      if (res.code === 200) {
        console.log("导入数据成功", res.data);
        this.isSearchImport = false;
        this.$message.success(`导入成功!`);
      } else {
        this.isSearchImport = false;
        this.$message.error(`导入失败!`);
      }
    },
    //导入常用词库状态改变
    changeSearchStatus() {
      this.isSearchImport = true;
    },
    resetData() {
      this.seen = "";
      this.tips = "";
      this.personal_seen = "";
      this.personal_tips = "";
    },
  },
};
</script>

<style scoped lang="less">
.formwork--wrap {
  box-sizing: border-box;
  padding: 0 20px;
  .formwork--title {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .formwork--title--l {
    display: flex;
    align-items: center;
    width: 65%;
  }
  .formwork--title--r {
    flex: 1 1 auto;
    .formwork--title--word {
      font-size: 16px;
      color: aqua;
      cursor: pointer;
    }
  }
  .formwork--btn {
    width: 88px;
    height: 32px;
    background-color: rgba(121, 121, 121, 0.15);
    color: rgba(255, 255, 255, 0.45);
    font-size: 16px;
    box-shadow: 0px 0px 3px 1px rgba(121, 121, 121, 1) inset;
    line-height: 32px;
    text-align: center;
    cursor: pointer;
    &:first-child {
      border-top-left-radius: 5px;
      border-bottom-left-radius: 5px;
    }
    &:last-child {
      border-top-right-radius: 5px;
      border-bottom-right-radius: 5px;
    }
    &.active {
      color: aqua;
      box-shadow: 0px 0px 3px 1px rgba(16, 185, 185, 1) inset;
    }
    &:hover {
      color: aqua;
      box-shadow: 0px 0px 3px 1px rgba(16, 185, 185, 1) inset;
    }
  }
  .formwork--con {
    width: 100%;
    height: 510px;
    overflow-y: auto;
    box-sizing: border-box;
    padding-right: 49px;
    .formwork--tree {
      width: 100%;
      height: 223px;
      padding-top: 20px;
    }
    .formwork--tips--sub {
      color: rgba(255, 255, 255, 0.85);
      font-size: 18px;
      margin: 15px 0;
    }
    .formwork--tips--inp {
      background-color: transparent !important;
      color: #fff;
      height: 230px !important;
      font-size: 16px;
      white-space: pre-line;
      outline: none !important;
      border: 1px solid rgba(255, 255, 255, 0.85) !important;
      border-radius: 4px;
      padding: 4px 11px;
    }
  }
  .keyboard--group2 {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    box-sizing: border-box;
    padding-top: 20px;
    .keyboard--item {
      width: 35px;
      height: 35px;
      color: #ffffff;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      margin: 15px 15px 15px 0;
      text-align: center;
      line-height: 35px;
      &.dis {
        cursor: not-allowed;
        &:hover {
          cursor: not-allowed;
        }
      }
    }
  }
  .symptom--tree--wrap2 {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    box-sizing: border-box;
    padding: 0;
  }
}
/*滚动条样式*/
.symptom--tree--wrap2::-webkit-scrollbar {
  width: 8px;
  /*height: 4px;*/
}
.symptom--tree--wrap2::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #fff;
}
.symptom--tree--wrap2::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 0;
  background: rgb(85, 83, 83);
}
/*滚动条样式*/
.formwork--con::-webkit-scrollbar {
  width: 8px;
  /*height: 4px;*/
}
.formwork--con::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #fff;
}
.formwork--con::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 0;
  background: rgb(85, 83, 83);
}
</style>
